package com.offcn.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.offcn.dao.SysMenuMapper;
import com.offcn.dao.SysRoleMapper;
import com.offcn.dao.SysUserMapper;
import com.offcn.pojo.SysMenu;
import com.offcn.pojo.SysRole;
import com.offcn.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;

    //认证操作 -- 做登录(验证)和授权
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过实参获取到了从登录页面送来的用户名
        //到用户表中根据用户名查找用户信息 -- 可能查到、可能没有查到
        QueryWrapper<SysUser>wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        //没有查找认证失败 -- 要么返回到登录页面、要么去到提示页面
        if(sysUser == null){
            System.out.println("************");
            throw new UsernameNotFoundException("用户名或者密码有误");
        }
        //如果查到认证成功
        Integer userId = sysUser.getId();
        //授权 -- 给当前用户绑定角色、绑定权限、绑定资源
        List<GrantedAuthority> list = new ArrayList<>();
        List<SysRole> roleList = sysRoleMapper.selectRoleByUserID(userId);
        for(SysRole sysRole : roleList){
            String roleCode = sysRole.getRoleCode();//admin
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + roleCode);
            list.add(authority);
        }
        List<SysMenu> menuList = sysMenuMapper.selectMenuByUserID(userId);
        for(SysMenu sysMenu : menuList){
            String perms = sysMenu.getPerms();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perms);
            list.add(authority);
        }
        //返回登录用户信息 -- 包含用户信息、角色、权限、资源 -- 用户信息也会保存到session
        return new User(username,sysUser.getPassword(),list);
    }
}
